package com.ss.android.image.loader;

import android.content.Context;
import android.widget.ImageView;

import com.bytedance.frameworks.baselib.network.http.util.TaskInfo;
import com.ss.android.image.BaseImageManager;
import com.ss.android.image.a.a.PicassoImage;

import java.util.LinkedHashMap;
import java.util.Map;

import pl.droidsonroids.gif.GifDrawable;

public class GifImageLoader extends ImageLoader {
    public static final class GifImageHolder {
        private final PicassoImage picassoImage;

        public GifImageHolder(PicassoImage picassoImage) {
            this.picassoImage = picassoImage;
        }
    }

    public Map<String, GifImageHolder> picassoImageHolderMap;
    public static Context context;
    public static BaseImageManager baseImageManager;
    private static TaskInfo taskInfo;
    private static volatile GifImageLoader instance;

    private GifImageLoader(Context context, TaskInfo taskInfo, BaseImageManager baseImageManager, int maxWidth) {
        super(context, taskInfo, 4, 8, 2, baseImageManager, maxWidth, -1, 0);
        this.picassoImageHolderMap = new LinkedHashMap();
    }

    public synchronized static GifImageLoader getInstance(Context context) {
        if (instance == null) {
            GifImageLoader.context = context;
            taskInfo = new TaskInfo();
            baseImageManager = new BaseImageManager(GifImageLoader.context);
            instance = new GifImageLoader(GifImageLoader.context, taskInfo, baseImageManager, context.getResources().getDisplayMetrics().widthPixels);
        }
        return instance;
    }

    public final void loadImage(String url, ImageView imageView, String filePath) {
        if (url != null && (imageView != null && (url.equals(imageView.getTag())))) {
            GifDrawable drawable = null;
            if (filePath != null) {
                try {
                    drawable = new GifDrawable(filePath);
                } catch (Throwable throwable) {
                }
            }

            GifImageHolder picassoImageHolder = this.picassoImageHolderMap.get(url);
            if (picassoImageHolder == null) {
                return;
            }

            if (drawable != null) {
                picassoImageHolder.picassoImage.setResult(drawable, true);
            } else {
                picassoImageHolder.picassoImage.setFailure(new Exception("loadImage exception"));
            }
            this.picassoImageHolderMap.remove(url);
        }
    }

    protected final boolean a() {
        return true;
    }
}

